import hashlib
import random
import requests
import time
from typing import Dict, Optional, Tuple
from config import settings

class BaiduTranslateService:
    """百度翻译API服务（新版本）"""
    
    def __init__(self):
        self.appid = settings.BAIDU_APPID
        self.secret_key = settings.BAIDU_SECRET_KEY
        # 使用新版本API
        self.token_url = "https://aip.baidubce.com/oauth/2.0/token"
        self.translate_url = "https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1"
        self.access_token = None
        
        # 语言代码映射
        self.lang_map = {
            "zh": "zh",      # 中文
            "en": "en",      # 英语
            "yue": "yue",    # 粤语
            "wyw": "wyw",    # 文言文
            "jp": "jp",      # 日语
            "kor": "kor",    # 韩语
            "fra": "fra",    # 法语
            "spa": "spa",    # 西班牙语
            "th": "th",      # 泰语
            "ara": "ara",    # 阿拉伯语
            "ru": "ru",      # 俄语
            "pt": "pt",      # 葡萄牙语
            "de": "de",      # 德语
            "it": "it",      # 意大利语
            "el": "el",      # 希腊语
            "nl": "nl",      # 荷兰语
            "pl": "pl",      # 波兰语
            "bul": "bul",    # 保加利亚语
            "est": "est",    # 爱沙尼亚语
            "dan": "dan",    # 丹麦语
            "fin": "fin",    # 芬兰语
            "cs": "cs",      # 捷克语
            "rom": "rom",    # 罗马尼亚语
            "slo": "slo",    # 斯洛文尼亚语
            "swe": "swe",    # 瑞典语
            "hu": "hu",      # 匈牙利语
            "cht": "cht",    # 繁体中文
            "vie": "vie",    # 越南语
            "lao": "lao",    # 老挝语
            "mya": "mya",    # 缅甸语
            "lisu": "auto",  # 傈僳语（百度不支持，使用自动检测）
        }
    
    def _get_access_token(self) -> Optional[str]:
        """获取访问令牌"""
        if not self.appid or not self.secret_key:
            return None
            
        try:
            params = {
                'grant_type': 'client_credentials',
                'client_id': self.appid,
                'client_secret': self.secret_key
            }
            response = requests.post(self.token_url, params=params, timeout=10)
            response.raise_for_status()
            result = response.json()
            
            if 'access_token' in result:
                self.access_token = result['access_token']
                return self.access_token
            else:
                print(f"获取token失败: {result}")
                return None
        except Exception as e:
            print(f"获取token异常: {e}")
            return None
    
    def _get_lang_code(self, lang: str) -> str:
        """获取百度API支持的语言代码"""
        return self.lang_map.get(lang, "auto")
    
    async def translate(self, text: str, from_lang: str, to_lang: str) -> Tuple[Optional[str], Optional[str]]:
        """
        翻译文本
        
        Args:
            text: 要翻译的文本
            from_lang: 源语言代码
            to_lang: 目标语言代码
            
        Returns:
            (翻译结果, 错误信息)
        """
        if not text.strip():
            return None, "翻译文本不能为空"
        
        # 如果源语言和目标语言相同，直接返回原文
        if from_lang == to_lang:
            return text, None
        
        # 检查API配置
        if not self.appid or not self.secret_key:
            return None, "百度翻译API配置未完成，请检查BAIDU_APPID和BAIDU_SECRET_KEY"
        
        # 获取访问令牌
        if not self.access_token:
            token = self._get_access_token()
            if not token:
                return None, "获取百度翻译API访问令牌失败"
        
        # 获取语言代码
        from_code = self._get_lang_code(from_lang)
        to_code = self._get_lang_code(to_lang)
        
        try:
            # 构建请求
            url = f"{self.translate_url}?access_token={self.access_token}"
            headers = {'Content-Type': 'application/json'}
            payload = {
                'q': text,
                'from': from_code,
                'to': to_code,
                'termIds': ''
            }
            
            # 发送请求
            response = requests.post(url, json=payload, headers=headers, timeout=10)
            response.raise_for_status()
            
            result = response.json()
            
            # 检查API返回结果
            if "error_code" in result:
                error_msg = self._get_error_message(result["error_code"])
                return None, f"翻译失败: {error_msg}"
            
            if "result" in result and "trans_result" in result["result"]:
                trans_results = result["result"]["trans_result"]
                if trans_results:
                    translated_text = trans_results[0]["dst"]
                    return translated_text, None
                else:
                    return None, "翻译结果为空"
            else:
                return None, f"翻译API返回异常: {result}"
                
        except requests.exceptions.RequestException as e:
            return None, f"网络请求失败: {str(e)}"
        except Exception as e:
            return None, f"翻译服务异常: {str(e)}"
    
    def _get_error_message(self, error_code: str) -> str:
        """获取错误码对应的错误信息"""
        error_messages = {
            "52001": "请求超时，请重试",
            "52002": "系统错误，请重试", 
            "52003": "未授权用户，请检查appid是否正确",
            "54000": "必填参数为空，请检查是否少传参数",
            "54001": "签名错误，请检查您的签名生成方法",
            "54003": "访问频率受限，请降低您的调用频率",
            "54004": "账户余额不足，请进行账户充值",
            "54005": "长query请求频繁，请降低长query的发送频率，3s后再试",
            "58000": "客户端IP非法，检查个人资料里填写的IP地址",
            "90107": "认证未通过或未生效，请前往我的认证查看认证进度"
        }
        return error_messages.get(error_code, f"未知错误码: {error_code}")

# 创建全局翻译服务实例
translate_service = BaiduTranslateService()



